#pragma once 
// client 和 server都包含了这个文件，就看到了同一份协议
#include "protocol.hpp"

namespace ns_client {
    class Client {
        private:
            uint16_t svr_port;
            std::string svr_ip;
            int sock;
        public:
            Client(uint16_t port, std::string ip) 
                :svr_port(port)
                ,svr_ip(ip)
                ,sock(-1)
            {}
            void initClient() {
                sock = socket(AF_INET, SOCK_STREAM, 0);
                if (sock < 0) {
                    std::cerr << "sock srror" << std::endl;
                    exit(2);
                }
            }
            void run() {
                struct sockaddr_in peer;
                bzero(&peer, sizeof(peer));
                peer.sin_family = AF_INET;
                peer.sin_port = htons(svr_port);
                peer.sin_addr.s_addr = inet_addr(svr_ip.c_str());
                std::cout << "asdsad" << std::endl;
                int ret = connect(sock, (struct sockaddr*)&peer, sizeof(peer));
                std::cout << "debug(ret): " << ret << std::endl;
                if (ret < 0) {
                    std::cerr << "connect error" << std::endl;
                    exit(3);
                }
                while (true) {
                    ns_protocol::request req;
                    std::cout << "请输入计算的两个数字： ";
                   // fflush(stdout);
                    std::cin >> req.x >> req.y;
                    std::cout << "请输入计算的符合：";
                    //fflush(stdout);
                    std::cin >> req.op;
                    send(sock, &req, sizeof(req), 0);
                    ns_protocol::response resp;
                    ssize_t s = recv(sock, &resp, sizeof(resp), 0);
                    if (s > 0) {
                        if (resp.code == 0) {
                            std::cout << req.x << req.op << req.y << "=" << resp.result << std::endl;
                        } else if(resp.code == 1) {
                            std::cout << "除0错误" << std::endl;
                        } else if (resp.code == 2) {
                            std::cout << "模0错误" << std::endl;
                        } else {
                            std::cout << "计算错误" << std::endl;
                        }
                    } else {
                        std::cout << "client recv error" << std::endl;
                        break;
                    } 
                }
            }
            ~Client() {
                if (sock >= 0) {
                    close(sock);
                }
            }
    };
}
